
<template>
  <div ref="chartRef" :style="{ height: height }" />
</template>

<script lang="ts">
export default {
  name: "BaseChart",
};
</script>
<script setup lang="ts">
import * as echarts from 'echarts';

const chartsArr: any[] = []

// 接收父组件传过来的数据
const { options = {}, height = '308px' } = defineProps<{
  options: any,
  height: string,
}>()

const instanceId = ref('')
const chartRef = ref()

const initCharts = () => {
  const chart1 = echarts.init(chartRef.value)
  chart1.setOption(options)
  chartsArr.push(chart1)
  instanceId.value = chart1.id

}
const updateChart = () => {
  const target = chartsArr.find(v => v.id === instanceId)
  if (target) {
    // 清空画布
    target.clear()
    // 解决echart宽高动态设置的情况下显示异常
    target.resize()
    // 重新设置配置项
    target.setOption(options)
  }

}
const resizeCharts = () => {
  for (var i = 0; i < chartsArr.length; i++) {
    chartsArr[i] && chartsArr[i].resize()
  }

}
onMounted(() => {
  initCharts()
  window.addEventListener('resize', resizeCharts)
})
onUnmounted(() => {
  // 移除窗口resize事件
  window.removeEventListener('resize', resizeCharts)
})

watch(() => options, () => {
  updateChart()
}, { deep: true })
</script>